package com.lyy.common.shiro;

import com.lyy.common.utils.ResultInfo;
import com.lyy.common.utils.ResultUtils;
import com.lyy.common.utils.SpringUtil;
import com.lyy.system.pojo.SysUser;
import com.lyy.system.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class JWTFilter extends BasicHttpAuthenticationFilter {

    /**
     * 对跨域提供支持
     *
     * @param request
     * @param response
     * @return
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        if (HttpMethod.OPTIONS.name().equalsIgnoreCase(WebUtils.toHttp(request).getMethod())) {
            return Boolean.TRUE;
        }
        String loginToken = JWTUtil.getToken(request);
        if (null != loginToken) {
            String username = JWTUtil.getUsername(loginToken);
            if (StringUtils.isNotBlank(username)) {
                SysUserService userService = SpringUtil.getBean(SysUserService.class);
                SysUser user = userService.getUserByUserName(username);
                if (null == user) {
                    log.info("无该用户:" + username);
                    JWTUtil.writeResponse(WebUtils.toHttp(response), HttpStatus.UNAUTHORIZED.value(), ResultUtils.getResult(ResultInfo.TOKEN_ERROR));
                    return false;
                }
                if (JWTUtil.verify(loginToken, username, user.getPassword())) {// 校验token是否正确
                    try {
                        executeLogin(request, response);
                        return true;
                    } catch (Exception e) {
                        JWTUtil.writeResponse(WebUtils.toHttp(response), HttpStatus.FORBIDDEN.value(), ResultUtils.getResult(ResultInfo.FORBIDDEN_ERROR));
                        return false;
                    }
                }
            }
        }
        JWTUtil.writeResponse(WebUtils.toHttp(response), HttpStatus.UNAUTHORIZED.value(), ResultUtils.getResult(ResultInfo.TOKEN_ERROR));
        return false;
    }

    /**
     * 执行登录
     */
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) {
        String loginToken = JWTUtil.getToken(request);
        if (StringUtils.isBlank(loginToken)) {
            return false;
        }
        JWTToken token = new JWTToken(loginToken);
        // 提交给realm进行登入，如果错误他会抛出异常并被捕获
        getSubject(request, response).login(token);
        // 如果没有抛出异常则代表登入成功，返回true
        return true;
    }

}